package com.weibo;

import java.util.ArrayList;

import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;

import com.weibo.aaweiboasync.AsyncDataLoader;
import com.weibo.aaweibobean.AccountInfo;
import com.weibo.aaweibobean.OAuthConstant;

/**
 * 欢迎界面
 * 
 * @author starry
 * 
 */
public class Front extends Activity {
	private Spinner accountSelector;
	private ImageButton login;
	private ImageButton adduser;
	private ImageButton exit;

	// private Button newAuthorize;

	private String userName;
	private String[] userNames;

	public static boolean isRemenber;
	public static boolean isAutoLogin;

	private LinearLayout loginLayout, authorizeLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.front);
		getViews();
		setListeners();
	}

	@Override
	protected void onResume() {
		super.onResume();
		setViews();
		authorizeLayout.setVisibility(View.GONE);
		loginLayout.setVisibility(View.GONE);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
		}
		return false;
	}

	private void getViews() {

		loginLayout = (LinearLayout) findViewById(R.id.loginLayout);
		authorizeLayout = (LinearLayout) findViewById(R.id.authorizeLayout);
		accountSelector = (Spinner) findViewById(R.id.front_accountSelector);
		login = (ImageButton) findViewById(R.id.front_login);
		adduser = (ImageButton) findViewById(R.id.front_adduser);
		exit = (ImageButton) findViewById(R.id.front_exit);
		// newAuthorize = (Button) findViewById(R.id.front_register);//新增授权
	}

	private void setViews() {
		userNames = getAccountNames();
		ArrayAdapter<?> accountSelectorAdapter = new ArrayAdapter<Object>(this,
				android.R.layout.simple_spinner_item, userNames);
		accountSelectorAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		accountSelector.setAdapter(accountSelectorAdapter);
	}

	private void setListeners() {

		accountSelector.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				userName = userNames[arg2];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		login.setOnClickListener(clickListener);
		adduser.setOnClickListener(clickListener);
		exit.setOnClickListener(clickListener);
		// newAuthorize.setOnClickListener(clickListener);
	}

	private OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.front_login:
				toMainTabs(userName);
				break;
			case R.id.front_adduser:// 用于授权
				new AsyncDataLoader(toAdduser).execute();
				break;
			case R.id.front_exit:
				System.exit(0);
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 进入MainTabs，开始显示首页（Home）
	 * 
	 * @param name
	 */
	private void toMainTabs(String name) {
		if (name == null || "".equals(name)) {
			WeiboToast.show(this, "微博帐号未授权，即将转入授权页面 ");
			new AsyncDataLoader(toAdduser).execute();
			return;
		} else {
			new AsyncDataLoader(toLogin).execute();
		}
	}

	/**
	 * 转入OAuth授权界面
	 */
	private void startOAuth() {
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		Weibo weibo = new Weibo();
		RequestToken requestToken;
		try {
			requestToken = weibo.getOAuthRequestToken("weibo4android://OAuthActivity");
			OAuthConstant.getInstance().setRequestToken(requestToken);
			Uri uri = Uri.parse(requestToken.getAuthenticationURL() + "&display=mobile");
			startActivity(new Intent(Intent.ACTION_VIEW, uri));
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 清除所有用户名列表
	 * 
	 * @return String[]
	 */
	private boolean deleteAccount() {
		SharedPreferences preferences = getSharedPreferences(AccountInfo.ACCOUNTS, MODE_PRIVATE);
		preferences.edit().clear();
		return true;
	}

	/**
	 * 获取用户名列表
	 * 
	 * @return String[]
	 */
	private String[] getAccountNames() {
		ArrayList<String> accounts = new ArrayList<String>();
		int i = 0;
		SharedPreferences preferences = getSharedPreferences(AccountInfo.ACCOUNTS, MODE_PRIVATE);
		while (preferences.contains(AccountInfo.NICK + i)) {
			String name = preferences.getString(AccountInfo.NICK + i, "");
			accounts.add(name);
			i++;
		}
		return accounts.toArray(new String[] {});
	}

	/**
	 * 获取用户信息 用户id & token & tokenSecret
	 * 
	 * @param name
	 *            用户名
	 * @return
	 */
	private Bundle getAccountInfo(String name) {
		Bundle bundle = new Bundle();
		SharedPreferences preferences = getSharedPreferences(AccountInfo.ACCOUNTS, MODE_PRIVATE);
		for (int i = 0; i < userNames.length; i++) {
			if (preferences.getString(AccountInfo.NICK + i, "").equals(name)) {
				String userId = preferences.getString(AccountInfo.ID + i, "");
				String token = preferences.getString(AccountInfo.TOKEN + i, "");
				String tokenSecret = preferences.getString(AccountInfo.TOKEN_SECRET + i, "");

				bundle.putString(AccountInfo.NICK, name);
				bundle.putString(AccountInfo.ID, userId);
				bundle.putString(AccountInfo.TOKEN, token);
				bundle.putString(AccountInfo.TOKEN_SECRET, tokenSecret);
				break;
			}
		}
		return bundle;
	}

	private AsyncDataLoader.Callback toLogin = new AsyncDataLoader.Callback() {

		@Override
		public void onStart() {
			Intent i = new Intent(Front.this, MainTabs.class);
			i.putExtras(getAccountInfo(userName));
			startActivity(i);

		}

		@Override
		public void onPrepare() {
			loginLayout.setVisibility(View.VISIBLE);
		}

		@Override
		public void onFinish() {

		}
	};

	private AsyncDataLoader.Callback toAdduser = new AsyncDataLoader.Callback() {

		@Override
		public void onStart() {
			startOAuth();
		}

		@Override
		public void onPrepare() {
			authorizeLayout.setVisibility(View.VISIBLE);
		}

		@Override
		public void onFinish() {

		}
	};

	void Log(String msg) {
		Log.i("weibo", "front--" + msg);
	}

}
